class Solution {
public:
    int lenLongestFibSubseq(vector<int>& arr) {
        int n = arr.size();
        vector<vector<int>> dp(n, vector<int>(n, 2));
        unordered_map<int, int> hash;

        for (int i = 0; i < n; ++i)
        {
            hash[arr[i]] = i;
        }

        int diff = 0;
        int maxl = 0;
        for (int i = 2; i < n; ++i)
        {
            for (int j = i - 1; j >= 0; --j)
            {
                diff = arr[i] - arr[j];
                if (diff < arr[j] && hash.count(diff) != 0)
                    dp[j][i] = dp[hash[diff]][j] + 1;
                // else
                //     dp[j][i] = 2;
                maxl = max(maxl, dp[j][i]);
            }
        }
        return maxl < 3 ? 0 : maxl;
    }
};